<?php

/**
   call API function

   @param  method     module.method
   @param  return     name of variable to assign the result to
   @param  forward    URL to forward or 'referer', use $return in URL
*/

if (isset($argv)) exit;    //dont't call from command line


function getCurrentCharset()
{
   if (array_key_exists('CONTENT_TYPE',$_SERVER))
   {
      $mathes = array();
      if (preg_match('/charset=(\S+)$/',$_SERVER['CONTENT_TYPE'],$mathes))
      {
         return $mathes[1];
      }
   }
   return 'cp1251';
}

$currentCharset = getCurrentCharset();

function convertCharset(&$val)
{
   global $currentCharset;
   if ($currentCharset != 'cp1251') {
      if (is_array($val)) 
      {
         array_walk($val,'convertCharset');
         return $val;
      }
      $val = iconv($currentCharset,'cp1251',$val);
   }
}

function params2MethodArgs($method, $params)
{
   $funcInfo = new ReflectionFunction($method);

   $args = array();
   foreach ($funcInfo->getParameters() as $paramInfo)
   {
      $nm = $paramInfo->getName();
      $val = null;

      if (!array_key_exists($nm,$params))
      {
         if ($paramInfo->isDefaultValueAvailable()) {
            $val = $paramInfo->getDefaultValue();
         }

         if (is_null($val) && !$paramInfo->isOptional()) {
            throw new Exception("Parameter [$nm] of [$method] can not be null");
         }
      }
      else 
      {
         $val = $params[$nm];
      }

      $classInfo = $paramInfo->getClass();
      if ($classInfo) {
         $val = eval("return new ".$classInfo->getName()."('$val');");
      }

      $args[] = $val;
   }


   return $args;
}


try 
{
   define('NO_REDIRECT',true);

   require_once 'init.inc';
   require_once CF_HOME.'params.inc';
   require_once CF_HOME.'json.php';

   list($module,$method) = explode('.',$par->get('method'));
   $module = strtolower($module);

   require_once CF_HOME."api/$module.php";

   $method = "cf\\api\\$module\\$method";
   
   if (!function_exists($method))
   {
      throw new Exception("invalid method - $method");
   }
   
   print_r($par->toArray());

   $res = call_user_func_array($method, params2MethodArgs($method, $par->toArray()));

   if ($par->exist('return')) 
   {
      $retVarName = param::get('return');
      $$retVarName = $res;
   }

   if ($par->exist('forward')) 
   {
      $url = param::get('forward');
      if ('referer' == $url) {
         $url = $_SERVER['HTTP_REFERER'];
      }
      else {
         eval('$url="'.$url.'";');
      }
      Page::redirect($url);
   }
   
   echo json_safe_encode($res);
}
catch (Exception $e)
{
   header("HTTP/1.0 500 Error occured");
   echo $e->getMessage();
}

?>